package com.probiz.estore.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.system.ShippingRate;
import com.probiz.estore.core.service.impl.GenericManagerImpl;
import com.probiz.estore.system.dao.ShippingRateDao;


/**
 * ShippingRate Business Delegate (Proxy) implementation to handle communication between web and
 * persistence layer. Implementation of ShippingRateManager interface.
 * Developer introduced interfaces should be declared here. Won't get overwritten.
 */
public class ShippingRateManagerImpl extends GenericManagerImpl<ShippingRate> implements com.probiz.estore.system.service.ShippingRateManager {
    private ShippingRateDao shippingRateDao = null;
    
    public void setShippingRateDao(ShippingRateDao shippingRateDao) {
		this.shippingRateDao = shippingRateDao;
	}
	@Override
	protected void initManager() {
		dao=shippingRateDao;
	}

	@Override
	protected void preDelete(ShippingRate entity) {
		
	}

	@Override
	protected void preSave(ShippingRate entity) {
		
	}

	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.ShippingRateManager#getShippingRateByRegionId(java.lang.Integer)
	 */
	public List<ShippingRate> getShippingRateByRegionId(Integer regionId){
		if(null == regionId){
			return new ArrayList<ShippingRate>();
		}else{
			return shippingRateDao.getShippingRateByRegionId(regionId);
		}
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.ShippingRateManager#getDifferentShipMethodRatesByRegionId(java.lang.Integer)
	 * m1 华南
	 * m1 广州
	 * m1 中国
	 * m2 广州
	 * m2 广东
	 * 条件：广州--->返回：m1 广州,m2 广州
	 * 条件：广东--->返回：m1 华南,m2 广东
	 * 条件：中国--->返回：m1 中国
	 * 
	 * 原理：使用regionType即可，因为它即为一个层级字段
	 */
	public List<ShippingRate> getDifferentShipMethodRatesByRegionId(Integer regionId){
		Map<Integer,ShippingRate> map = new HashMap<Integer,ShippingRate>();
		List<ShippingRate> shippingRateList = getShippingRateByRegionId(regionId);
		for(ShippingRate shippingRate:shippingRateList){
			if(map.containsKey(shippingRate.getShippingMethodId())){
				ShippingRate preRate = map.get(shippingRate.getShippingMethodId());
				if(shippingRate.getRegion().getRegionType() > preRate.getRegion().getRegionType()){
					map.put(shippingRate.getShippingMethodId(), shippingRate);
				}
			}else{
				map.put(shippingRate.getShippingMethodId(), shippingRate);
			}
		}
		List<ShippingRate> result = new ArrayList<ShippingRate>();
		for(ShippingRate shippingRate: map.values()){
			result.add(shippingRate);
			//force load shippingMethod
			shippingRate.getShippingMethod().getShippingMethodName();
		}
		return result;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.ShippingRateManager#getRegionShippingRates(java.lang.Boolean, java.lang.Integer)
	 */
	public List<ShippingRate> getDifferentShipMethodRatesByRegionId(Boolean isCod, Integer regionId){
		List<ShippingRate> result = new ArrayList<ShippingRate>();
		List<ShippingRate> shippingRateList = getDifferentShipMethodRatesByRegionId(regionId);
		
		if (isCod != null && isCod) {
			//筛选出支持货到付款的配送方式
			for (ShippingRate shippingRate: shippingRateList) {
				if(shippingRate.getShippingMethod().getIsCod() != null && Constants.FLAG_TRUE.equals(shippingRate.getShippingMethod().getIsCod())) {
					result.add(shippingRate);
				}
			}
		} else {
			result.addAll(shippingRateList);
		}
		
		return result;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.system.service.ShippingRateManager#getShippingExpence(java.lang.Integer, java.math.BigDecimal)
	 */
	public BigDecimal getShippingExpence(Integer shippingRateId,BigDecimal weight) {
		BigDecimal sum=new BigDecimal(0);
		if(shippingRateId!=null){
			ShippingRate shippingRate=shippingRateDao.getById(shippingRateId);
			if(shippingRate!=null){
				sum=shippingRate.getBasePrice();
				if(weight!=null&&shippingRate.getBaseWeight()!=null){
					//单位增量或费率为空(0)时，没额外费用---只有基本费用getBasePrice()
					//计费公式：总运费 = 基本运费 + [（商品重量 - 起价重量）÷ 单位增量] × 费率
					if(shippingRate.getIncreaseUnit()!=null&&shippingRate.getIncreaseUnit().compareTo(BigDecimal.valueOf(0.000000000001))>0&&shippingRate.getWeightPerRate()!=null&&shippingRate.getWeightPerRate().compareTo(BigDecimal.valueOf(0.000000000001))>0){
						String weightUnit = ConfigUtil.getInstance().getWeightUnit();
						BigDecimal newWeigth=weight;
						if(shippingRate.getMetricUnitCode()!=null) {
							if(!weightUnit.equalsIgnoreCase(shippingRate.getMetricUnitCode())){//商品重与快递计费单位不同时,转换商品重量
								if("g".equalsIgnoreCase(weightUnit)&&"kg".equalsIgnoreCase(shippingRate.getMetricUnitCode())){
									newWeigth=newWeigth.divide(BigDecimal.valueOf(1000));
								}else if("kg".equalsIgnoreCase(weightUnit)&&"g".equalsIgnoreCase(shippingRate.getMetricUnitCode())){
									newWeigth=newWeigth.multiply(BigDecimal.valueOf(1000));
								}
							}
						}
						if(newWeigth.compareTo(shippingRate.getBaseWeight())>0.000000000001){//超重
							System.out.println("---------------------------------------------"+weightUnit+","+shippingRate.getMetricUnitCode());
							sum=sum.add(newWeigth.subtract(shippingRate.getBaseWeight()).divide(shippingRate.getIncreaseUnit(),0,BigDecimal.ROUND_CEILING).multiply(shippingRate.getWeightPerRate()));
							logger.debug("【" + "基本运费 + [（商品重量 - 起价重量）÷ 单位增量] × 费率:"+shippingRate.getBasePrice()+"+("+newWeigth+"-"+shippingRate.getBaseWeight()+")%"+shippingRate.getIncreaseUnit()+"*"+shippingRate.getWeightPerRate()+"="+sum+"】");
						}
					}
				}
				
			}
		}		
		return sum;
	}
	
}
